import echarts from "echarts";
import zrender from "zrender";
import { addCircleToChart, animateRotate } from "./base";
import { toRad } from "../utils";

const elements = {};

function draw(chart, percentage) {
  let gradient = new echarts.graphic.RadialGradient(0.5, 0.5, 0.5, [
    { offset: 0, color: "rgba(0, 0, 0, 0)" },
    { offset: 1, color: "rgba(0, 138, 175, 0.5)" }
  ]);

  let zr = chart.getZr();
  let cx = zr.getWidth() / 2;
  let cy = zr.getHeight() / 2;

  let arcOpts = [
    {
      startAngle: 10,
      endAngle: 170,
      reverse: false
    },
    {
      startAngle: 190,
      endAngle: 350,
      reverse: false
    },
  ];

  arcOpts.forEach(arcOpt => {
    let arc = new zrender.Arc({
      origin: [cx, cy],
      shape: {
        cx: cx,
        cy: cy,
        r: 60,
        startAngle: toRad(arcOpt.startAngle),
        endAngle: toRad(arcOpt.endAngle)
      },
      style: {
        fill: null,
        stroke: '#12718E',
        strokeOpacity: 0.8,
        lineWidth: 2
      }
    });

    animateRotate(arc);
    zr.add(arc);

  });

  let circle = new zrender.Circle({
    origin: [cx, cy],
    shape: {
      cx: cx,
      cy: cy,
      r: 50
    },
    style: {
      fill: gradient,
      fillOpacity: 0.5,
      stroke: "#009adb",
      lineWidth: 2,
      text: percentage + '%',
      fontSize: "20",
      textFill: "#009adb"
    }
  });

  drawGauge(chart)
  addCircleToChart(chart, 60, 2, 180);
  addCircleToChart(chart, 60, 2, 360);
  zr.add(circle);
  drawLine(zr, cx, cy);

  elements.circle = circle;
}

function drawGauge(chart) {
  let option = {
    series: [
      {
        type: 'gauge',
        detail: {
          show: false,
          formatter: '{value}%'
        },
        startAngle: 0,
        endAngle: 360,
        axisLine: {
          show: false,
        },
        radius: '57%',
        splitLine: {
          show: false,
        },
        axisLabel: {
          show: false
        },
        axisTick: {
          length: 3,
          lineStyle: {
            color: '#0192BB',
          }
        }
      },

    ]
  };

  chart.setOption(option);
}

function drawLine(zr, cx, cy) {

  let lineOpts = [
    {
      x1: cx + 50,
      y1: cy,
      x2: cx + 45,
      y2: cy
    },
    {
      x1: cx - 50,
      y1: cy,
      x2: cx - 45,
      y2: cy
    },
    {
      x1: cx,
      y1: cy - 50,
      x2: cx,
      y2: cy - 45
    },
    {
      x1: cx,
      y1: cy + 50,
      x2: cx,
      y2: cy + 45
    },
  ]
  lineOpts.forEach(opt => {
    let line = new zrender.Line({
      origin: [cx, cy],
      shape: opt,
      style: {
        stroke: '#0898C1',
        lineWidth: 2
      },
      z: 2
    });
    // animateRotate(line, false);
    zr.add(line);
  });

}



function update(percentage) {
  elements.circle.attr({
    style: {
      text: percentage + '%',
    }
  });
}


export default {
  draw,
  update
}
